package com.aplink.dellcommercial.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.aplink.dellcommercial.activities.LoginActivity;
import com.aplink.dellcommercial.configuration.DellController;
import com.aplink.dellcommercial.database.DellDataTable;
import com.aplink.dellcommercial.fragments.LoginFragment;
import com.aplink.generic.pojo.GenericAttribute;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DellCommercialUtility {
    private static String previousDateString( String dateString )
            throws ParseException {
        // Create a date formatter using your format string
        final DateFormat dateFormat = new SimpleDateFormat( "yyyymmdd",
                Locale.getDefault() );

        // Parse the given date string into a Date object.
        // Note: This can throw a ParseException.
        final Date myDate = dateFormat.parse( dateString );

        // Use the Calendar class to subtract one day
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime( myDate );
        calendar.add( Calendar.DAY_OF_YEAR, - 1 );

        // Use the date formatter to produce a formatted date string
        final Date previousDate = calendar.getTime();
        final String result = dateFormat.format( previousDate );

        return result;
    }

    public static void checkConnect( Context mContext ) {
        final ConnectivityManager connect = (ConnectivityManager) mContext
                .getSystemService( Context.CONNECTIVITY_SERVICE );
        final NetworkInfo infoWifi = connect
                .getNetworkInfo( ConnectivityManager.TYPE_WIFI );
        final NetworkInfo infoMobile = connect
                .getNetworkInfo( ConnectivityManager.TYPE_MOBILE );

        if ( infoWifi.isConnected() || infoMobile.isConnected() ) {
            DellController.setOnline( true );
        } else {
            DellController.setOnline( false );
        }
    }

    public static ArrayList<GenericAttribute<String, String>> getExpireDay(
            String TokenExpiryDate ) throws ParseException {
        int day = 0;
        int month = 0;
        int year = 0;
        final String date = TokenExpiryDate;// jsonResult.getString("TokenExpiryDate");
        final String[] elements = date.split( "/" );
        if ( elements.length > 0 ) {
            day = Integer.parseInt( elements[0] );
            month = Integer.parseInt( elements[1] );
            year = Integer.parseInt( elements[2].toString().substring( 0, 4 )
                    .toString() );
        }

        final String elementForTime = date.split( " " )[1];

        int hour = Integer.parseInt( elementForTime.split( ":" )[0] );
        final int minute = Integer.parseInt( elementForTime.split( ":" )[1] );
        final int second = Integer.parseInt( elementForTime.split( ":" )[2] );

        final String timestampt = date.split( " " )[2];
        final String pmTime = "pm";
        if ( timestampt.toLowerCase( Locale.getDefault() ).contains( pmTime ) == true ) {
            hour += 12;
        }

        if ( ( hour == 0 ) && ( day == 1 ) && ( month == 1 ) ) {
            hour = 23;
            day = 31;
            month = 12;
            year--;
        } else if ( ( hour == 0 ) && ( day == 1 ) ) {
            day = Integer.parseInt( previousDateString( String.valueOf( year )
                    + String.valueOf( month ) + String.valueOf( day ) ) );
            hour = 23;
            month--;
        } else if ( hour == 0 ) {
            String monthFormat = "";
            String dayFormat = "";
            if ( month < 10 ) {
                monthFormat = "0" + month;
            }
            if ( day < 10 ) {
                dayFormat = "0" + day;
            }
            day = Integer.parseInt( previousDateString( String.valueOf( year )
                    + String.valueOf( monthFormat ) + String.valueOf( dayFormat ) ) );
            System.out.println( "day = " + day );
            hour = 23;
        } else {
            hour--;
        }

        // we wrap TokenExpriedDate into Calendar variable
        final Calendar tokenExpriedCal = Calendar.getInstance();

        tokenExpriedCal.set( Calendar.YEAR, year );
        tokenExpriedCal.set( Calendar.MONTH, month - 1 ); // since it runs from 0
        // index
        tokenExpriedCal.set( Calendar.DAY_OF_MONTH, day );
        tokenExpriedCal.set( Calendar.HOUR_OF_DAY, hour );
        tokenExpriedCal.set( Calendar.MINUTE, minute );
        tokenExpriedCal.set( Calendar.SECOND, second );

        // we get currentTime based on Calendar instance
        Calendar currentCal = Calendar.getInstance();
        // add interval logout time for this currentLogin time
        currentCal.add( Calendar.MINUTE, LoginFragment.intervalTimeMinute );

        // we compare this newExpriedLocalTime with TokenExpriedDate
        if ( currentCal.compareTo( tokenExpriedCal ) > 0 ) {
            // this expriedLocal is after expriedTokenDate
            // we assign again the expriedLocal by expriedTokenDate to make sure
            // it must always be earlier than tokenExpriedCal
            currentCal = tokenExpriedCal;

        } // otherwise, this newExpriedLocalDate is valid

        // we set currentCal as newLocalTimeOut in sharepreference
        final long expiredServer = tokenExpriedCal.getTimeInMillis();
        final long expiredLocal = currentCal.getTimeInMillis();

        final ArrayList<GenericAttribute<String, String>> genericAttributes = new ArrayList<GenericAttribute<String, String>>();

        genericAttributes.add( new GenericAttribute<String, String>(
                DellDataTable.UserLoginInfo.EXPRIED_LOCAL, String
                .valueOf( expiredLocal ) ) );
        genericAttributes.add( new GenericAttribute<String, String>(
                DellDataTable.UserLoginInfo.EXPRIED_SERVER, String
                .valueOf( expiredServer ) ) );
        return genericAttributes;
    }

    public static void checkExpireDay( String TokenExpiryDate )
            throws ParseException {
        int day = 0;
        int month = 0;
        int year = 0;
        String date = TokenExpiryDate;// jsonResult.getString("TokenExpiryDate");
        String[] elements = date.split( "/" );
        if ( elements.length > 0 ) {
            day = Integer.parseInt( elements[0] );

            month = Integer.parseInt( elements[1] );

            year = Integer.parseInt( elements[2].toString().substring( 0, 4 )
                    .toString() );
        }

        String elementForTime = date.split( " " )[1];

        int hour = Integer.parseInt( elementForTime.split( ":" )[0] );
        int minute = Integer.parseInt( elementForTime.split( ":" )[1] );
        int second = Integer.parseInt( elementForTime.split( ":" )[2] );

        String timestampt = date.split( " " )[2];
        String pmTime = "pm";
        if ( timestampt.toLowerCase().contains( pmTime ) == true ) {
            hour += 12;
        }
        if ( hour == 0 && day == 1 && month == 1 ) {
            hour = 23;
            day = 31;
            month = 12;
            year--;
        } else if ( hour == 0 && day == 1 ) {
            day = Integer.parseInt( previousDateString( String.valueOf( year )
                    + String.valueOf( month ) + String.valueOf( day ) ) );
            System.out.println( "day = " + day );
            hour = 23;
            month--;
        } else if ( hour == 0 ) {
            String monthFormat = "";
            String dayFormat = "";
            if ( month < 10 ) {
                monthFormat = "0" + month;
            }
            if ( day < 10 ) {
                dayFormat = "0" + day;
            }
            day = Integer.parseInt( previousDateString( String.valueOf( year )
                    + String.valueOf( monthFormat ) + String.valueOf( dayFormat ) ) );
            System.out.println( "day = " + day );
            hour = 23;
        } else {
            hour--;
        }

        // we wrap TokenExpriedDate into Calendar variable
        Calendar tokenExpriedCal = Calendar.getInstance();

        tokenExpriedCal.set( Calendar.YEAR, year );
        tokenExpriedCal.set( Calendar.MONTH, month - 1 ); // since it runs from 0
        // index
        tokenExpriedCal.set( Calendar.DAY_OF_MONTH, day );
        tokenExpriedCal.set( Calendar.HOUR_OF_DAY, hour );
        tokenExpriedCal.set( Calendar.MINUTE, minute );
        tokenExpriedCal.set( Calendar.SECOND, second );

        Calendar currentCal = Calendar.getInstance();

        currentCal.add( Calendar.MINUTE, LoginFragment.intervalTimeMinute );

        if ( currentCal.compareTo( tokenExpriedCal ) > 0 ) {
            currentCal = tokenExpriedCal;

        }
        long expiredServer = tokenExpriedCal.getTimeInMillis();
        long expiredLocal = currentCal.getTimeInMillis();

        DellController.getInstance().setExpiredServer(
                String.valueOf( expiredServer ) );
        DellController.getInstance().setExpiredLocal(
                String.valueOf( expiredLocal ) );

    }

    public static void showAlertDialog( Context context, int icon,
                                        String message, String title ) {
        final AlertDialog.Builder builder = new AlertDialog.Builder( context );
        builder.setTitle( title ).setMessage( message ).setIcon( icon );
        builder.setCancelable( false ).setPositiveButton( android.R.string.ok,
                null );
        builder.create().show();
    }

    public static void showLogoutDialog( final Activity context, int icon,
                                         String message, String title ) {
        final AlertDialog.Builder builder = new AlertDialog.Builder( context );
        builder.setTitle( title ).setMessage( message ).setIcon( icon );
        builder.setCancelable( false ).setPositiveButton( android.R.string.ok,
                null );
        builder.setPositiveButton( android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick( DialogInterface dialog, int which ) {
                        logout( context );
                    }
                } );
        builder.create().show();
    }

    public static void logout( Activity mActivity ) {
        DellController.getInstance().setLogin( false );
        Intent intent = new Intent( mActivity, LoginActivity.class );
        mActivity.finish();
        intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK );
        mActivity.startActivity( intent );
    }

    public static int checkTimeValidation() {
        try {
            int isLoginState = 0;
            long currentCal = Calendar.getInstance().getTimeInMillis();
            long serverTimeout = Long.parseLong( DellController
                    .getInstance().getExpiredServer() );
            long localTimeout = Long.parseLong( DellController
                    .getInstance().getExpiredLocal() );
            if ( currentCal > serverTimeout ) {
                DellController.getInstance().setCheckLog( true );
                isLoginState = 0;
                DellController.getInstance().setExpiredLocal( "" );
                DellController.getInstance().setExpiredServer( "" );
            } else if ( currentCal > localTimeout ) {
                isLoginState = 1;
                DellController.getInstance().setExpiredLocal( "" );
            } else {
                isLoginState = 2;
            }
            return isLoginState;
        } catch ( NumberFormatException e ) {
            return 1;
        }
    }

    public static void setLocalTimeExpiry() {
        Calendar currentCal = Calendar.getInstance();
        currentCal.add( Calendar.MINUTE, LoginFragment.intervalTimeMinute );
        long expiredLocal = currentCal.getTimeInMillis();
        DellController.getInstance().setExpiredLocal(
                String.valueOf( expiredLocal ) );
    }
}
